//@ts-check

const express = require('express');
const fs=require('fs');
const path=require('path')
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
const app = express();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.static('./'))

// app.post('/setaya', (req, res) => {

// })
function resolve(dir){
    return path.resolve(__dirname,'../data',dir)
}
app.post('/addya', function (req, res, next) {
    var params=req.body;
    //文件目录检索
    var username=params.username;
    var dirpath=resolve(username);
    //创建一个专属目录
    if(!fs.existsSync(dirpath)){
        fs.mkdirSync(dirpath);
    }
    //创建按年份分类
    var yearPath=path.resolve(dirpath,params.year)
    if(!fs.existsSync(yearPath)){
        fs.mkdirSync(yearPath);
    }
    //创建月度目标
    var filePath=path.resolve(yearPath,params.month+".json");
    
    fs.writeFileSync(filePath,JSON.stringify(params.target));
    res.json({code:200});
  });

  app.post('/getya', function (req, res) {
    var params=req.body;
    //文件目录检索
    var username=params.username;
    var dirpath=resolve(username);
    //创建一个专属目录
    if(!fs.existsSync(dirpath)){
        fs.mkdirSync(dirpath);
    }
    //创建按年份分类
    var yearPath=path.resolve(dirpath,params.year)
    if(!fs.existsSync(yearPath)){
        fs.mkdirSync(yearPath);
    }
    //创建月度目标
    var filePath=path.resolve(yearPath,params.month+".json");
    if(!fs.existsSync(filePath)){
        res.json({
            code:404
        })
    }else{
        var content=fs.readFileSync(filePath,'utf8');
        res.json(JSON.parse(content));
    }
  });

app.listen(8001, () => {
    console.log('\033[42;30m DONE \033[40;32m server begin at port 8001，http://localhost:8001  \033[0m')
});